import * as React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, StackNavigationProp, TransitionSpecs } from '@react-navigation/stack';

type RootStackParamList = {
  ScreenA: undefined;
  ScreenB: undefined;
};

type ScreenAProps = {
  navigation: StackNavigationProp<RootStackParamList, 'ScreenA'>;
};

type ScreenBProps = {
  navigation: StackNavigationProp<RootStackParamList, 'ScreenB'>;
};

const ScreenA: React.FC<ScreenAProps> = ({ navigation }) => {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Screen A</Text>
      <Button
        title="Replace with Screen B"
        onPress={() => navigation.replace('ScreenB')}
      />
    </View>
  );
};

const ScreenB: React.FC<ScreenBProps> = ({ navigation }) => {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Screen B</Text>
      <Button
        title="Replace with Screen A"
        onPress={() => navigation.replace('ScreenA')}
      />
    </View>
  );
};

const Stack = createStackNavigator<RootStackParamList>();

export default function TestAnimationTypeForReplace() {
  const [animationType, setAnimationType] = React.useState<'push' | 'pop'>('push');

  // 自定义动画时长
  const slowTransitionSpec = {
    open: {
      animation: 'timing',
      config: {
        duration: 1500,
      },
    },
    close: {
      animation: 'timing',
      config: {
        duration: 1500,
      },
    },
  };

  return (
    <View style={{ flex: 1 }}>
      <View style={styles.switchBar}>
        <Button
          title="动画: push"
          color={animationType === 'push' ? '#0081f1' : '#aaa'}
          onPress={() => setAnimationType('push')}
        />
        <Button
          title="动画: pop"
          color={animationType === 'pop' ? '#0081f1' : '#aaa'}
          onPress={() => setAnimationType('pop')}
        />
        <Text style={{ marginLeft: 10 }}>当前动画: {animationType}</Text>
      </View>
      <NavigationContainer>
        <Stack.Navigator
          initialRouteName="ScreenA"
          screenOptions={{
            animationTypeForReplace: animationType,
            headerShown: true,
            transitionSpec: slowTransitionSpec,
          }}
        >
          <Stack.Screen name="ScreenA" component={ScreenA} />
          <Stack.Screen name="ScreenB" component={ScreenB} />
        </Stack.Navigator>
      </NavigationContainer>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1, alignItems: 'center', justifyContent: 'center',
  },
  title: {
    fontSize: 28, marginBottom: 20,
  },
  switchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#eee',
    zIndex: 1,
  },
});